import us from "../../api/user"
const state={
    isLogin:localStorage.getItem('token')?true:false,
    useInfo:{},
    Permissions:[],
    PagePermission:["look","add", "modify", "delete", "other"],
}
const mutations={
    setLoginState(state,b){
        state.isLogin=b
    },
    setUserInfo(state,b){
        state.useInfo=b
    },
    setPermissions(state,b){
        state.Permissions=b;
    }
}
const actions={
    login({commit},user){
        //请求登录
        return us.login(user).then(res=>{
            const {code,token}=res.data;
            if(code){
                //登录成功
                commit("setLoginState",true)
                localStorage.setItem("token",token)
            }
            return code;
        })
    },
    logout({commit}){
        //清除缓存
        localStorage.removeItem("token")
        //重置状态
        commit("setLoginState",false)
        commit("setUserInfo",{})
        commit("setPermissions",[])
    },
    getInfo({commit,state}){
        return new Promise((resolve,reject)=>{
            us.getUseInfo().then(res=>{
                const {code,userInfo,pagePermission}=res.data
                if(!code){
                    reject('Verification failed, please Login again.')
                }
                commit("setUserInfo",userInfo)
                commit("setPermissions",pagePermission)
                resolve(res.data)
            }).catch(err=>{
                reject(err)
            })
        })
    }
}
export default {
    namespaced:true,
    state,
    mutations,
    actions
}